package com.warrantyhotel.android.ui;

import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.warrantyhotel.android.R;
import com.warrantyhotel.android.model.Keys;
import com.warrantyhotel.android.service.UpdateNewsServise;
import com.warrantyhotel.android.util.HttpConnector;
import com.warrantyhotel.android.util.JSONParser;
import com.warrantyhotel.android.util.MyPreferences;
import com.warrantyhotel.android.util.ToastUtil;
import com.warrantyhotel.android.widget.TakeImageDialog;

public class HomeActivity extends FragmentActivity {
	private WarrantyApplication app;
	private TextView firstName;
	private TextView logout;
	private ImageView avatar;
	private Uri mCapturedImageURI;
	private static final int SELECT_PHOTO = 23;
	private static final int IMAGE_PICKER_REQUEST = 24;
	private static final int LOGOUT = 25;
	private static SharedPreferences prefs;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home);

		app = (WarrantyApplication) getApplicationContext();

		prefs = PreferenceManager.getDefaultSharedPreferences(this);

		avatar = (ImageView) findViewById(R.id.item_image);
		firstName = (TextView) findViewById(R.id.first_name_home);
		logout = (TextView) findViewById(R.id.logout);
		CharSequence styledText = getResources().getText(R.string.logout);
		logout.setText(styledText, TextView.BufferType.SPANNABLE);

		String avatart_uri = prefs.getString(Keys._avatar, null);
		if (null != avatart_uri && !TextUtils.isEmpty(avatart_uri)) {
			setLogoFromGallery(Uri.parse(avatart_uri), avatar);
		}

		checkIsNewsServiceRunning();

		IntentFilter intentFilter = new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION);
		registerReceiver(receiverConnection, intentFilter);
		new UpdateCountryState().execute(new String[1]);

	}

	BroadcastReceiver receiverConnection = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle extras = intent.getExtras();
			if (extras != null) {
				boolean isInetEnable = extras.getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY);
				if (isInetEnable) {
					ToastUtil.showText(getApplicationContext(), getString(R.string.conn_avaliable));
				}
			}

		}
	};

	@Override
	protected void onResume() {
		super.onResume();
		if (prefs.getString(Keys._firstName, null) == null && prefs.getString(Keys._lastName, null) == null) {
			firstName.setText(getString(R.string.enter_your_information));
			firstName.setOnClickListener(new android.view.View.OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(getApplicationContext(), SettingsActivity.class);
					startActivity(intent);
				}
			});
		} else {
			if (prefs.contains(Keys._firstName)) {
				firstName.setText(prefs.getString(Keys._firstName, ""));
				firstName.append(" ");
			}
			if (prefs.contains(Keys._lastName)) {
				firstName.append(prefs.getString(Keys._lastName, ""));
			}

		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_logout, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.logout_on_menu:
			showDialog(LOGOUT);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private boolean isSDPresent() {
		return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
	}

	public void changeIcon(View view) {
		new TakeImageDialog(this, new Runnable() {
			@Override
			public void run() {
				// take new photo
				if (isSDPresent()) {
					String fileName = "avatar.jpg";
					ContentValues values = new ContentValues();
					values.put(MediaStore.Images.Media.TITLE, fileName);
					mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
					MyPreferences.setUri(HomeActivity.this, mCapturedImageURI.toString());
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
					startActivityForResult(intent, SELECT_PHOTO);
				} else {
					ToastUtil.showText(getApplicationContext(), getString(R.string.no_sdcard));
				}

			}
		}, new Runnable() {
			@Override
			public void run() {
				// use current image from Android gallery
				final Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
				intent.setType("image/*");
				startActivityForResult(intent, IMAGE_PICKER_REQUEST);
			}
		}).show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
		super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

		switch (requestCode) {
		case SELECT_PHOTO:
			if (resultCode == RESULT_OK) {
				Uri uri = Uri.parse(MyPreferences.getUri(HomeActivity.this));
				setLogoFromGallery(uri, avatar);
			}
			break;
		case IMAGE_PICKER_REQUEST:
			if (resultCode == RESULT_OK) {
				Uri selectedImage = imageReturnedIntent.getData();
				setLogoFromGallery(selectedImage, avatar);
			}
			break;
		}
	}

	private void setLogoFromGallery(Uri uri, ImageView imageView) {

		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		String capturedImageFilePath = cursor.getString(column_index_data);
		cursor.close();

		InputStream imageStream = null;
		try {
			imageStream = getContentResolver().openInputStream(uri);
			Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream, null, getBitmapOptions(4));
			ExifInterface exifInterface = new ExifInterface(capturedImageFilePath);
			int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
			switch (orientation) {
			// horizontal on Samsung Galaxy S2
			case 6:
				Matrix mtx = new Matrix();
				mtx.postRotate(90);
				// Rotating Bitmap
				yourSelectedImage = Bitmap.createBitmap(yourSelectedImage, 0, 0, yourSelectedImage.getWidth(), yourSelectedImage.getHeight(), mtx, true);
				break;
			default:
				break;
			}

			imageView.setImageBitmap(yourSelectedImage);
		} catch (Exception e) {
			e.printStackTrace();
			imageView.setImageResource(R.drawable.icon_warranty);
		}

		if (prefs.contains(Keys._remembeMe) && prefs.getBoolean(Keys._remembeMe, false) && uri != null) {
			final Editor edit = prefs.edit();
			edit.putString(Keys._avatar, uri.toString());
			edit.commit();
		}

	}

	private BitmapFactory.Options getBitmapOptions(int scale) {
		BitmapFactory.Options _bitmapOptions = null;
		if (_bitmapOptions == null) {
			_bitmapOptions = new BitmapFactory.Options();
			// _bitmapOptions.inTempStorage = new byte[256];
			_bitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
			_bitmapOptions.inJustDecodeBounds = false; // this will request the
														// bm
			_bitmapOptions.inSampleSize = scale; // scaled down by 4
		}
		return _bitmapOptions;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(receiverConnection);
		if (null != app && null != app.getTimer())
			app.getTimer().cancel();
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		switch (id) {
		case LOGOUT:

			builder.setTitle(getString(R.string.logout_suggest));
			builder.setPositiveButton(getString(R.string.ok), new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					clearCredential();
					finish();
					Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
					startActivity(intent);
				}
			});
			builder.setNegativeButton(getString(R.string.cancel), new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {

				}
			});

			builder.setCancelable(true);
			return builder.create();
		}

		return null;
	}

	private void clearCredential() {
		// TODO
		final Editor edit = prefs.edit();
		edit.remove(Keys._password);
		edit.remove(Keys._username);
		edit.commit();
	}

	public void checkIsNewsServiceRunning() {

		boolean isSetNewsUpdate = prefs.getBoolean(Keys.checkNews, false);

		if (isSetNewsUpdate) {

			ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
			for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
				if ("com.warrantyhotel.android.service.UpdateNewsServise".equals(service.service.getClassName())) {
					return;
				}
			}
			Intent intent = new Intent(getApplicationContext(), UpdateNewsServise.class);
			startService(intent);

		}
	}

	private class UpdateCountryState extends AsyncTask<String, Void, Void> {

		@Override
		protected Void doInBackground(String... params) {
			final HttpConnector connector = HttpConnector.getInstance();
			final JSONParser parser = new JSONParser(getApplicationContext().getContentResolver(), HomeActivity.this);

			String countryUrl = null;
			String response = null;
			try {
				countryUrl = "Country/List";
				response = connector.sendGETRequest(countryUrl);
				parser.parseCountryJSON(new JSONObject(response));

				countryUrl = "CountryState/List";
				response = connector.sendGETRequest(countryUrl);
				parser.parseStateJSON(new JSONObject(response));

				countryUrl = "Language/List";
				response = connector.sendGETRequest(countryUrl);
				parser.parseLanguageJSON(new JSONObject(response));

			} catch (JSONException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (URISyntaxException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}

			return null;
		}

	}

}
